var express = require("express");
var path = require("path");

var app = express();
var artTemplate = require("express-art-template");

app.engine("html", artTemplate);

app.set("views", path.join(__dirname, "views"));
var mongoose = require("mongoose");

mongoose.connect(
  "mongodb://127.0.0.1:27017/Rep",
  {
    useNewUrlParser: true,
    useUnifiedTopology: true
  },
  function(err) {
    if (err) {
      console.log(err);
      console.log("数据库连接失败");
    } else {
      console.log("数据库连接成功");
    }
  }
);

var Message = mongoose.model("mes", {
  time1: String,
  time2: String,
  host: String,
  txt: String,
  replay: Array
});

app.get("/mess", function(req, res) {
  var txt = req.query.txt;
  var now = new Date();
  var time1 =
    now.getFullYear() + "年" + now.getMonth() + 1 + "月" + now.getDate() + "日";
  var time2 = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
  var host = "127.0.0.1";
  var replay = [];
  var data = { time1, time2, host, txt, replay };
  
  var stu = new Message(data);
  // 向数据库插入一条数据
  stu.save(function(err) {
    if (err) {
      console.log(err);
      console.log("保存失败");
    } else {
      console.log("保存成功");
    }
  });
  res.redirect("/");
});

app.get("/Replay/:aid", function(req, res) {
  var txt = req.query.txt;
  var now = new Date();
  var time1 =
    now.getFullYear() + "年" + now.getMonth() + 1 + "月" + now.getDate() + "日";
  var time2 = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
  var host = req.ip;
  var id=req.params.aid
  

  
  

  Message.updateOne(
    {
      _id: mongoose.mongo.ObjectId(id.substr(1,24))
    },
    {
      $push: {
        replay: { time1: time1, time2: time2, host: host, txt: txt }
      }
    },
    function(err) {
      if (err) {
          console.log(err);
        console.log("更新失败");
        // res.send("更新失败");
      } else {
        // res.send("更新成功");
        console.log("更新成功");
      }
    }
  );
  res.redirect("/");
});

app.get("/", function(req, res) {
  Message.find(function(err, content) {
    if (err) {
      console.log("查询失败");
      
    } else {
      console.log("查询成功");
      console.log(content);
      res.render("index.html", { content });
    }
  });
});

app.listen(5555, function() {
  console.log("服务器启动...");
});
